[Leetcode] 3. Longest Substring Without Repeating Characters

meidum

Given a string, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution1:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# DFS solution O(n2)
if not s:
return 0
memo = set()
self.max_length = float('-inf')
for i in range(len(s)):
if self.max_length >= len(s) - i:
break
self.helper("", i, s, memo)
return self.max_length

def helper(self, path, ind, string, memo):
self.max_length = max(self.max_length, len(path))
if ind >= len(string):
return

if string[ind] not in path:
path+=string[ind]
# print(path)
self.helper(path, ind+1, string, memo)
return

class Solution2:
# sliding window
# O(2n) time O(min(m, n)) space. m is 26, n is len of str
def lengthOfLongestSubstring(self, s):
if not s:
return 0
i = j = 0
res = 0
memo = set()
while i < len(s) and j < len(s):
if s[j] not in memo:
memo.add(s[j])
res = max(res, j - i + 1)
j+=1
else:
memo.remove(s[i])
i += 1
return res

class Solution:
# sliding window optimized using map
# O(n) time O(min(m, n)) space. m is 26, n is len of str
def lengthOfLongestSubstring(self, s):
if not s:
return 0
res = 0
i = j = 0
dic = {}
while j < len(s):
if s[j] in dic:
i = max(dic[s[j]], i)
res = max(res, j - i + 1)
dic[s[j]] = j + 1
j+=1
return res